﻿Imports HslCommunication
Imports HslCommunication.Profinet.Siemens
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Public Class Form1
    Dim StripperPLC As SiemensS7Net
    'PLC是否连接成功
    Dim StripperPlcConFLG As Boolean = False
    Dim ping = New Net.NetworkInformation.Ping()
    Dim objClsSysParam As New clsSysParam
    Dim agv_website As String
    Dim objagvlog As New clsAgvLog
    Dim objtmj As New clsTmj
    Dim objtask As New clsTask
    Dim objProdInfo As New clsProdInfo
    Dim httphelper As New HttpHelper
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        connectDB()
        'Label2.Text = "本机IP：" & GetIPAddr()
        initStripperPLC()
        initAgvWebSite()
    End Sub
    ''' <summary>
    ''' 连接数据库
    ''' </summary>
    Private Sub connectDB()

        g_szInitFileName = My.Application.Info.DirectoryPath & "\tmj_agv.ini"

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

    End Sub

    Private Sub initStripperPLC()
        StripperPLC = New SiemensS7Net(SiemensPLCS.S1200)
        StripperPLC.IpAddress = lblIp.Text
        StripperPLC.Port = 102
        StripperPLC.Rack = 0
        StripperPLC.Slot = 0
        StripperPLC.ConnectionType = 1
        StripperPLC.LocalTSAP = 258
        Try
            Dim pingResult As Net.NetworkInformation.PingReply = ping.Send(lblIp.Text)
            If pingResult.Status = Net.NetworkInformation.IPStatus.Success Then
                Dim connect As OperateResult = StripperPLC.ConnectServer()
                If connect.IsSuccess = True Then
                    StripperPlcConFLG = connect.IsSuccess
                    lblStatus.Text = "连接结果成功"
                    Me.Refresh()
                End If
            Else
                lblStatus.Text = "Ping失败！"
            End If
        Catch ex As Exception
            lblStatus.Text = "连接失败！"
        End Try
    End Sub

    Private Sub initAgvWebSite()
        Dim dt As DataTable = objClsSysParam.selectAgvWebSite()
        If dt.Rows.Count = 1 Then
            agv_website = dt.Rows(0)("param_value").ToString()
        End If
    End Sub

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
        '查询最新的一条脱模记录
        If MsgBox("确认要启动该AGV吗？", vbYesNo, "提示") = vbYes Then
            'Dim dt As DataTable = objtmj.selectTmj()
            Dim dt As DataTable = objClsSysParam.selectAgvTmj()
            Label2.Text = "AGV:" & dt.Rows(0)("param_value").ToString()
            Dim b1 As Boolean = writeStripperBoolPlc("DB47.DBX11.1", True)
            If b1 Then
                writeStripperBoolPlc("DB47.DBX11.0", False)
                writeStripperBoolPlc("DB47.DBX11.3", False)
                Dim localip As String = GetIPAddr()
                objagvlog.add(localip, dt.Rows(0)("param_value").ToString(), "启动", "脱模机下agv启动")
                Dim rtnms1g As Integer = objtmj.update_agv_start2(1, dt.Rows(0)("param_explain").ToString())
                If rtnms1g <> -2 Then
                    If dt.Rows(0)("param_explain").ToString().Equals("0") = False Then
                        objProdInfo.updateTuoMo(dt.Rows(0)("param_explain").ToString(), "脱模机")
                        objtask.task_transfer(dt.Rows(0)("param_explain").ToString())
                        Dim rtnmsg As String = setTask(dt.Rows(0)("param_value").ToString(), 1)
                        If rtnmsg.Equals("ok") Then
                            objClsSysParam.update_agv_tmj("0", "0")
                            MsgBox("启动成功")
                        Else
                            MsgBox("错误信息：" & rtnmsg)
                        End If
                    End If
                Else
                    MsgBox("启动脱模机数据失败")
                End If
            Else
                MsgBox("AGV送货结果写入：失败")
            End If
        End If
    End Sub

    Private Function setTask(agv As String, oper As Integer) As String
        Dim msg As String
        If String.IsNullOrEmpty(agv_website) = False Then
            Dim url As String = agv_website & "AGVAPI?do=SetAGVState&agv=" & agv & "&oper=" & oper
            Dim rtn As String = httphelper.HttpGet(url, "")
            Dim jo As JObject = JsonConvert.DeserializeObject(rtn)
            Dim code As String = jo("code").ToString() '输出0
            msg = jo("msg").ToString() '输出ok
        Else
            msg = "请联系工作人员，配置agv网址"
        End If
        Return msg
    End Function

    Private Function writeStripperBoolPlc(place As String, val As Boolean) As Boolean
        'If StripperPlcConFLG_UC Then
        Return WriteStripperBool(place, val, StripperPLC)
        'Else
        '    Return False
        'End If
    End Function
    Private Function WriteStripperBool(place As String, val As Boolean, plc As SiemensS7Net) As Boolean
        '查询脱模机状态等条件
        'Dim dt As DataTable = objStripper.getList(strippername)
        'If dt.Rows(0)("status").ToString().Equals("1") Then
        '    '如果满足条件 则进行更新
        'End If
        Dim OperR As OperateResult = plc.Write(place, val)
        Return OperR.IsSuccess
    End Function

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If MsgBox("确认要进行关闭吗？", vbYesNo, "提示") = vbYes Then
            If StripperPlcConFLG Then
                StripperPLC.ConnectClose()
            End If
        Else
            e.Cancel = True
        End If
    End Sub

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        DBacs.Disconnect()
    End Sub

    Private Sub btnAgv_Click(sender As Object, e As EventArgs) Handles btnAgv.Click
        Form2.ShowDialog()
    End Sub
End Class
